package com.ysd.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.exception.RRException;
import com.ysd.modules.app.dao.ChaptersDao;
import com.ysd.modules.app.dao.PracticeResultDao;
import com.ysd.modules.app.dao.TopicDao;
import com.ysd.modules.app.entity.ChapterEntity;
import com.ysd.modules.app.entity.PracticeResult;
import com.ysd.modules.app.entity.TopicEntity;
import com.ysd.modules.app.service.ChaptersService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChaptersServiceImpl extends ServiceImpl<ChaptersDao, ChapterEntity> implements ChaptersService {
    @Resource
    private PracticeResultDao practiceResultDao;
    @Resource
    private TopicDao topicDao;

    /**
     * 查询课程下的所有的章节
     *
     * @return
     */
    @Override
    public List<ChapterEntity> getChapterList(Integer courseId,Integer stuId, Integer type) {
        if (courseId == null || courseId == 0){
            throw new RRException("课程id不能为0或者为null");
        }
        if (stuId == null || stuId == 0){
            throw new RRException("学生id不能为0或者为null");
        }
        QueryWrapper<ChapterEntity> qw = new QueryWrapper<>();
        qw.eq("status", 1);
        qw.eq("course_id", courseId);
        qw.orderByAsc("order_num");
        List<ChapterEntity> chapterEntityList = baseMapper.selectList(qw);
        if(chapterEntityList == null || chapterEntityList.size() == 0){
            throw new RRException("未查询到相对应的课程章节信息");
        }
        for (int i = 0; i < chapterEntityList.size(); i++) {
            ChapterEntity chapterEntity = chapterEntityList.get(i);
            QueryWrapper<PracticeResult> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("target_id", chapterEntity.getId());
            queryWrapper.eq("stu_id", stuId);
            queryWrapper.eq("type", type);
            PracticeResult practiceResult = practiceResultDao.selectOne(queryWrapper);
            if (practiceResult == null) {
                chapterEntity.setAccuracy("0");
                chapterEntity.setAnswerNum(0);
            }else{
                chapterEntity.setAccuracy(practiceResult.getAccuracy());
                chapterEntity.setAnswerNum(practiceResult.getAnswerNum());
            }
            /**
             * 查询总数量
             */
            QueryWrapper<TopicEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("chapter_id",chapterEntity.getId());
            int count = topicDao.selectCount(queryWrapper1);
            chapterEntity.setSum(count);
        }
        return chapterEntityList;
    }
}
